<template>
    <div>
        <el-input :value="$route.query.roleName" disabled size="small"></el-input>
        <el-tree :data="assignList" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current
            :props="defaultProps">
        </el-tree>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="$router.replace({ name: 'Role' })">取消</el-button>
    </div>
</template>

<script>
export default {
    data() {
        return {
            assignList: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            }
        }
    },
    mounted() {
        this.getAssignList()
    },
    methods: {
        // 获取角色权限列表
        async getAssignList() {
            let roleId = this.$route.query.id
            let result = await this.$API.permission.toAssign(roleId)
            this.assignList = result.data.children
            const checkedIds = this.getCheckedIds(this.assignList)
            this.$refs.tree.setCheckedKeys(checkedIds)
        },

        // 得到所有的选中的id列表
        getCheckedIds(auths, initArr = []) {
            console.log(auths);
            return auths.reduce((pre, item) => {
                if (item.select && item.level === 4) {
                    pre.push(item.id)
                } else if (item.children) {
                    this.getCheckedIds(item.children, initArr)
                }
                return pre
            }, initArr)
        },


        // 点击保存按钮
        async save() {
            var ids = this.$refs.tree.getCheckedKeys().join(",")
            console.log(ids);
            await this.$API.permission.doAssign(this.$route.query.id, ids)
            this.$message.success('分配权限成功')
            // 必须在跳转前获取(跳转后通过this获取不到正确的数据了)
            const roleName = this.$route.query.roleName
            const roles = this.$store.getters.roles
            this.$router.replace('/acl/role', () => {
                // 跳转成功后, 判断如果更新的是当前用户对应角色的权限, 重新加载页面以获得最新的数据
                if (roles.includes(roleName)) {
                    // window.location.reload()
                }
            })
        }

    },
}
</script>

<style scoped>

</style>